"use strict";

const Package = require("@pengsg-cli/package");
const log = require("@pengsg-cli/log");
const path = require("path");
const cp = require('child_process');

const SETING = {
  init: "@imooc-cli/init",
};

const CACHE_DIR = 'dependencies';

async function exec() {
  const commandObj = arguments[arguments.length - 1];
  const packageName = SETING[commandObj.name()];
  const packageVersion = "latest";
  let pkg = null;
  let targetPath = process.env.CLI_TARGET_PATH;
  if (targetPath) {
    pkg = new Package({ targetPath, packageName, packageVersion });
  } else {
    targetPath = path.join(process.env.CLI_HOME,CACHE_DIR)
    const storePath = path.resolve(targetPath,'node_modules')
    pkg = new Package({ targetPath,storePath, packageName, packageVersion });
    if (await pkg.exist()) {
      // 安装package
      await pkg.install();
    } else {
      // 更新package
      await pkg.update();
    }
  }
  
  const rootDir = pkg.getRootFilePath();
  if(rootDir){
    try {
      // require(rootDir).call(null,Array.from(arguments))
      //这里使用node多进程进行动态命令执行
      const args = Array.from(arguments);
      const cmdObj = args[args.length-1];
      const o = Object.create(null);
      Object.keys(cmdObj).forEach(key => {
        if(cmdObj.hasOwnProperty(key) && !key.startsWith('_') && (key !== 'parent') ){
          o[key] = cmdObj[key]
        }
      });
      args[args.length-1] = o;
      const code = `require("${rootDir}").call(null,${JSON.stringify(args)})`;
      const child = cp.spawn('node',['-e',code],{
        cwd: process.cwd(),
        stdio: 'inherit'
      })
      child.on('error',e => {
        log.error(e.message);
        process.exit(1)
      })
      child.on('exit',e => {
        log.verbose('执行完毕');
        process.exit(e)
      })
    } catch (error) {
      log.error(error)
    }
    
  }
}

module.exports = exec;
